package com.cgnpc.scp.purchase.service.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cgnpc.cuddemo.funcInstance.service.ICudFileService;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.framework.service.IBpmCenterService;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.pojo.ActivityInfoParams;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.BpmUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.purchase.mybatis.entity.*;
import com.cgnpc.scp.purchase.mybatis.mapper.client.*;
import com.cgnpc.scp.purchase.service.ICloseProcessService;
import com.cgnpc.scp.purchase.service.IPurchaseContractItemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/******************************
 * 用途说明: 调试采购-需求关闭审批流程
 * 作者姓名: chenshijie
 * 创建时间: 2020/09/19 19:12
 ******************************/
@Service
public class CloseProcessServiceImpl implements ICloseProcessService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContractProcessServiceImpl.class);

    private static final String ACTIVITY_NAME_010 = "010_需求人提交年度采购需求关闭申请";

    private static final String ACTIVITY_NAME_020 = "020_计划协调员审批";

    private static final String ACTIVITY_NAME_030 = "030_调试采购主管审批";


    @Autowired
    IBpmCenterService bpmCenterService;

    @Autowired
    ICudFileService cudFileService;

    @Autowired
    CloseProcessApplyMapper closeProcessApplyMapper;

    @Autowired
    CloseProcessItemMapper closeProcessItemMapper;

//    @Autowired
//    PurchaseContractItemMapper purchaseContractItemMapper;

    @Autowired
    CloseProcessAuditMapper closeProcessAuditMapper;

    @Autowired
    CurrentUser currentUser;

    @Autowired
    private IPurchaseContractItemService purchaseContractItemService;

    @Autowired
    private ViewCloseDemandMapper viewCloseDemandMapper;

    @Autowired
    ContractProcessItemMapper contractProcessItemMapper;

    /**********************************
     * 用途说明: 新建采购需求关闭审批流
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult insertContract(String params) throws Exception {
        Map map = JSONObject.parseObject(params);

        map.put("folio","年度采购需求关闭审批流-" +
                new SimpleDateFormat("yyyyMMdd").format(new Date()));

        Map contractMap = (Map) map.get("win");

        CloseProcessApply closeProcessApply = (CloseProcessApply) BpmUtil.mapToObjectByJson(contractMap, CloseProcessApply.class);

        closeProcessApply.setProcInstId("0");

        //判断是否为保存草稿
        if (!StringUtils.isEmpty(map.get("isSaveDraft"))) {
            //先处理业务
            modifyApplyInfo(closeProcessApply);
            //设置流程实例相关的列表ID  可用  针对流程的formInstID
            map.put("appFormId", closeProcessApply.getId());
            //保存草稿  假如从草稿修改过来，isModifyDraft为Y
            if (StringUtils.isEmpty(map.get("isModifyDraft"))) {
                return bpmCenterService.addDraft(map);
            }

            return ApiResult.success() ;
        } else {
            //先处理业务
            modifyApplyInfo(closeProcessApply);
            //设置流程实例相关的列表ID  可用  针对流程的formInstID
            map.put("appFormId", closeProcessApply.getId());
            //启动流程
            return bpmCenterService.startProcess(map);
        }
    }

    private void modifyApplyInfo(CloseProcessApply closeProcessApply) {
        // 根据id判断之前是否已经保存过数据,有则更新，无则插入
        if (StringUtil.isNullOrSpace(closeProcessApply.getId())) {
            closeProcessApply.setId(IDHelper.uuid());
            closeProcessApply.setCreateTime(new Date());
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            closeProcessApply.setCreateUser(userinfo.getUserId());
            closeProcessApply.setCreateUserName(userinfo.getUserName());
            closeProcessApplyMapper.insert(closeProcessApply);
            insertItem(closeProcessApply);
        } else {
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            closeProcessApply.setLastUpdateUser(userinfo.getUserId());
            closeProcessApply.setLastUpdateUserName(userinfo.getUserName());
            closeProcessApply.setLastUpdateTime(new Date());
            closeProcessApplyMapper.updateById(closeProcessApply);

//            CloseProcessItemExample closeProcessItemExample = new CloseProcessItemExample();
//            closeProcessItemExample.createCriteria().andApplyIdEqualTo(closeProcessApply.getId());
//            closeProcessItemMapper.deleteByExample(closeProcessItemExample);

            QueryWrapper<CloseProcessItem> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("apply_id", closeProcessApply.getId());
            closeProcessItemMapper.delete(queryWrapper);

            insertItem(closeProcessApply);
        }

    }

    private void insertItem(CloseProcessApply closeProcessApply) {
        for (ViewCLoseDemand item : closeProcessApply.getViewCLoseDemandList()) {
            CloseProcessItem closeProcessItem = new CloseProcessItem();
            closeProcessItem.setItemId(item.getId());
            closeProcessItem.setId(IDHelper.uuid());
            closeProcessItem.setApplyId(closeProcessApply.getId());
            closeProcessItemMapper.insert(closeProcessItem);
        }
    }

    /**********************************
     * 用途说明: 获取环节业务数据
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public Object getActivityBusinessInfo(ActivityInfoParams activityInfoParams) throws Exception {
        if (ACTIVITY_NAME_010.equals(activityInfoParams.getActivityName())) {
            return getApplyById(activityInfoParams);
        } else if (ACTIVITY_NAME_020.equals(activityInfoParams.getActivityName()) ||
                ACTIVITY_NAME_030.equals(activityInfoParams.getActivityName())) {
            return getProcessAudit(activityInfoParams);
        } else {
            throw new ScpException("activity not found.");
        }
    }

    /**********************************
     * 用途说明: 根据id获取采购需求关闭审批流程申请信息
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public CloseProcessApply getApplyById(ActivityInfoParams activityInfoParams) throws Exception {
        CloseProcessApply closeProcessApply = null;
        if (!StringUtil.isNullOrSpace(activityInfoParams.getId())) {
            closeProcessApply = closeProcessApplyMapper.selectById(activityInfoParams.getId());
        } else if (!StringUtil.isNullOrSpace(activityInfoParams.getProcInstId())) {
//            CloseProcessApplyExample closeProcessApplyExample = new CloseProcessApplyExample();
//            closeProcessApplyExample.createCriteria().andProcInstIdEqualTo(activityInfoParams.getProcInstId());
//            List<CloseProcessApply> closeProcessApplies = closeProcessApplyMapper.selectByExample(closeProcessApplyExample);

            QueryWrapper<CloseProcessApply> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("proc_inst_id", activityInfoParams.getProcInstId());
            List<CloseProcessApply> closeProcessApplies = closeProcessApplyMapper.selectList(queryWrapper);

            if (closeProcessApplies.size() > 0) {
                closeProcessApply = closeProcessApplies.get(0);
            }
        } else {
            throw new ScpException("params error");
        }

        if (closeProcessApply == null) {
            throw new ScpException("details is missing");
        }

//        QueryWrapper<CloseProcessItem> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("apply_id", closeProcessApply.getId());
//        List<CloseProcessItem> closeProcessItems = closeProcessItemMapper.selectList(queryWrapper);
//
//        if (closeProcessItems != null && closeProcessItems.size() > 0) {
//            List<String> itemIds = new ArrayList<>();
//            for (CloseProcessItem closeProcessItem : closeProcessItems) {
//                itemIds.add(closeProcessItem.getItemId());
//            }
//
//            List<PurchaseContractItem> purchaseContractItems = purchaseContractItemService.loadByIdList(itemIds);
//
//            closeProcessApply.setPurchaseContractItemList(purchaseContractItems);
//        }

        QueryWrapper<ViewCLoseDemand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_id", closeProcessApply.getId());
        List<ViewCLoseDemand> viewChangeDemands = viewCloseDemandMapper.selectList(queryWrapper);
        closeProcessApply.setViewCLoseDemandList(viewChangeDemands);

        return closeProcessApply;
    }

    /**********************************
     * 用途说明: 根据流程实例id获取经理审批信息
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public CloseProcessAudit getProcessAudit(ActivityInfoParams activityInfoParams) throws Exception {
        if (StringUtil.isNullOrSpace(activityInfoParams.getProcInstId())) {
            throw new ScpException("procInstId is missing.");
        }
//        CloseProcessAuditExample closeProcessAuditExample = new CloseProcessAuditExample();
//        closeProcessAuditExample.createCriteria().
//                andProcInstIdEqualTo(activityInfoParams.getProcInstId()).
//                andActNameEqualTo(activityInfoParams.getActivityName());
//        List<CloseProcessAudit> closeProcessAudits = closeProcessAuditMapper.selectByExample(closeProcessAuditExample);

        QueryWrapper<CloseProcessAudit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proc_inst_id", activityInfoParams.getProcInstId()).eq("act_name",activityInfoParams.getActivityName());
        List<CloseProcessAudit> closeProcessAudits = closeProcessAuditMapper.selectList(queryWrapper);

        if (closeProcessAudits.size() > 0) {
            return closeProcessAudits.get(0);
        }
        return null;
    }

    /**********************************
     * 用途说明: 删除业务数据以及草稿
     * 参数说明 paramsMap
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult deleteApplyAndMyDraft(Map paramsMap) throws Exception {
        String formId = paramsMap.get("id").toString();
        if (StringUtil.isNullOrSpace(formId)) {
            throw new ScpException("params error");
        }

        closeProcessApplyMapper.deleteById(formId);

//        CloseProcessItemExample closeProcessItemExample = new CloseProcessItemExample();
//        closeProcessItemExample.createCriteria().andApplyIdEqualTo(formId);
//        closeProcessItemMapper.deleteByExample(closeProcessItemExample);

        QueryWrapper<CloseProcessItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("apply_id", formId);
        closeProcessItemMapper.delete(queryWrapper);

        ApiResult apiResult = bpmCenterService.deleteMyDraft(paramsMap);

        return apiResult;
    }

    /**********************************
     * 用途说明: 提交流程
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult submitProcess(String params) throws Exception {
        Map map = JSONObject.parseObject(params);
        // 流程除了启动环节，任意环节提交时均要保存流程实例id
        String procInstId = map.get("procInstId").toString();
        if (StringUtil.isNullOrSpace(procInstId)) {
            throw new ScpException("procInstId is missing.");
        }

        // 根据环节名称判断当前处理逻辑
        String act_name = map.get("act_name").toString();
        if (ACTIVITY_NAME_020.equals(act_name) ||
                ACTIVITY_NAME_030.equals(act_name)) {
            processAudit(map);
        } else {
            throw new ScpException("activity not found.");
        }

        //判断是前进还是后退
        String flag = map.get("deal_answer").toString();
        ApiResult apiResult = null;
        if ("1".equals(flag)) {
            if(ACTIVITY_NAME_030.equals(act_name)) {
                // 更新需求状态为已关闭
                String appFormId = map.get("formInstID").toString();

                QueryWrapper<CloseProcessItem> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("apply_id", appFormId);
                List<CloseProcessItem> closeProcessItems = closeProcessItemMapper.selectList(queryWrapper);
                for(CloseProcessItem closeProcessItem: closeProcessItems) {
                    ContractProcessItem contractProcessItem = new ContractProcessItem();
                    contractProcessItem.setId(closeProcessItem.getItemId());
                    contractProcessItem.setDemandType(3);
                    contractProcessItemMapper.updateById(contractProcessItem);
                }

            }
            apiResult = bpmCenterService.submitworklistitem(map);
        } else if ("2".equals(flag)) {
            apiResult = bpmCenterService.rollBackAction(map);
        }
        return apiResult;
    }

    /**********************************
     * 用途说明: 审批
     * 参数说明 params
     * 返回值说明:
     ***********************************/
    @Override
    public void processAudit(Map map) throws Exception {
        // 流程除了启动环节，任意环节提交时均要保存流程实例id
        String procInstId = map.get("procInstId").toString();
        String deal_answer = map.get("deal_answer").toString();
        String auditNote = map.get("auditNote").toString();
        String act_name = map.get("act_name").toString();

        //根据procInstId查询业务表是否有数据
//        CloseProcessAuditExample closeProcessAuditExample = new CloseProcessAuditExample();
//        closeProcessAuditExample.createCriteria().
//                andProcInstIdEqualTo(procInstId).
//                andActNameEqualTo(act_name);
//        List<CloseProcessAudit> closeProcessAudits = closeProcessAuditMapper.selectByExample(closeProcessAuditExample);

        QueryWrapper<CloseProcessAudit> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("proc_inst_id", procInstId).eq("act_name",act_name);
        List<CloseProcessAudit> closeProcessAudits = closeProcessAuditMapper.selectList(queryWrapper);

        if (closeProcessAudits.size() > 0) {
            //业务数据存在执行更新操作
            CloseProcessAudit closeProcessAudit = closeProcessAudits.get(0);
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            closeProcessAudit.setLastUpdateUser(userinfo.getUserId());
            closeProcessAudit.setLastUpdateUserName(userinfo.getUserName());
            closeProcessAudit.setLastUpdateTime(new Date());
            closeProcessAudit.setProcInstId(procInstId);
            closeProcessAudit.setDealAnswer(Integer.parseInt(deal_answer));
            closeProcessAudit.setAuditNote(auditNote);
            closeProcessAuditMapper.updateById(closeProcessAudit);

        } else {
            //业务数据不存在执行插入操作
            CloseProcessAudit closeProcessAudit = new CloseProcessAudit();
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            closeProcessAudit.setCreateUser(userinfo.getUserId());
            closeProcessAudit.setCreateUserName(userinfo.getUserName());
            closeProcessAudit.setCreateTime(new Date());
            closeProcessAudit.setProcInstId(procInstId);
            closeProcessAudit.setId(IDHelper.uuid());
            closeProcessAudit.setActName(act_name);
            closeProcessAudit.setDealAnswer(Integer.parseInt(deal_answer));
            closeProcessAudit.setAuditNote(auditNote);
            closeProcessAuditMapper.insert(closeProcessAudit);
        }
    }
}
